package io.renren.modules.iots.utils.socket.client;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.SocketChannel;
import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.renren.modules.iots.entity.IOTPBean;
import io.renren.modules.iots.utils.comment.Code;
import io.renren.modules.iots.utils.comment.HandleOfIotpbeanType;
import io.renren.modules.iots.utils.comment.IotpBodyUtils;
import io.renren.modules.iots.utils.comment.Msg_rellect;

/**
 * @ClassName: SingleSocketClientThread
 * @Description: 单例模式SingleSocketClientThread类
 * @author 周西栋
 * @date 2018年5月8日
 *
 */
public class SingleSocketReadThread implements Runnable {
	
	private Integer reccount = 0;
	// 创建读取的缓冲区
    ByteBuffer buffer = ByteBuffer.allocate(8354);
	
	/**
	 * 日志
	 */
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	/**
	 * TCP字节数组流切片拼接工具
	 */
	Msg_rellect mr = null;
	
	/**
	 * 协议转换工具
	 */
	IotpBodyUtils ibu = null;
	
	/************************************************      单例模式     ************************************************/
	
    /**
     * 创建一个新的实例 SingleSocketClientThread.
     */
    private SingleSocketReadThread() {
    	new Thread(this).start();
    }
    
    /**
     * 私有对象变量
     */
    private static final SingleSocketReadThread single = new SingleSocketReadThread();
    
    /**
     * @Title: getInstance
     * @Description: 饿汉模式--单例（静态工厂方法） 
     * @param @return    参数
     * @return SingleSocketClientThread    返回类型
     * @throws
     */
    public static SingleSocketReadThread getInstance() {
        return single;
    }
	
	/************************************************      单例模式     ************************************************/
	
	@Override
	public void run() {
		logger.info("我启动了一个读信息的线程");
        // 轮询访问selector
        while (!SocketUtils.SOCKETBEAN_MAP.isEmpty()) {
        	try {
				Thread.sleep(1);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
        	for(SocketBean socketBean :SocketUtils.SOCKETBEAN_MAP.values()){
        		try {
        			if(socketBean.getConnectstatus() == 3 ){
        				try {
        					if(socketBean.getSocketChannel() != null){
								readBuffer(socketBean);
							}
						} catch (CancelledKeyException e) {
							continue;
						}
        			}
				} catch (IOException e) {
					e.printStackTrace();
					continue;
				}
        	}
        }
	}
	
    /**
     * @Title: readBuffer
     * @Description: 从缓冲区中读取数据
     * @param @param socketBean
     * @param @throws IOException    参数
     * @return void    返回类型
     * @throws
     */
    public void readBuffer(SocketBean socketBean) throws IOException{
    	SocketChannel channel = socketBean.getSocketChannel();
        if(!channel.isConnected()){
        	logger.info("客户端【 "+channel.getRemoteAddress()+" 】是不是处于连接状态： "+channel.isConnected());
        	return;
        }
        try {
			reccount = channel.read(buffer);
		} catch (IOException e) {
			reccount = -1;
			logger.info("************* ************* ************* 我出错了 ************* ************* *************");
		}
        if(reccount == -1){
        	logger.info("断开..." + channel.socket().getRemoteSocketAddress());  
            String address = channel.socket().getRemoteSocketAddress().toString().split("/")[1];
            logger.info("address:"+address);
            SocketUtils.SOCKETBEAN_MAP.get(address).setConnectstatus(4);
        }else if(reccount > 0){
        	buffer.flip();
        	// 协议转换工具
        	this.ibu = SocketUtils.CHANNEL_IOTPBODYUTILS_MAP.get(socketBean);
        	byte[] data = this.ibu.getNewByteArray(buffer.array(), 0, reccount);
        	byte[] iotp_result = null;// 返回通讯的结果(返回值)
        	// 信息拼接工具
        	this.mr = SocketUtils.RELLECTMESSAGE.get(socketBean);
        	List<byte[]> rellect_list =  this.mr.rellect(data);
        	if(rellect_list != null){
        		for(byte[] byte_array : rellect_list){
        			IOTPBean iotp = this.ibu.toIotpBean(byte_array);
        			Code code = this.ibu.getIotp_code().get(iotp);
        			if(iotp != null && iotp.getBody() != null){
            			
            			logger.info("从服务端【 "+channel.getRemoteAddress()+" 】收到的信息转成可读内容" );
            			iotp_result = this.ibu.getResult(iotp, code);
//            			channel.write(ByteBuffer.wrap(iotp_result));
//            			logger.info("向服务端【 "+channel.getRemoteAddress()+" 】发送的反馈信息是：" + Arrays.toString(iotp_result));
            			
            			// 将有效的信息 放到相应的队列里
            			sendKafka(iotp);
            		}
        		}
        	}
    		buffer.clear();
        }
    }
    
    /**
     * @Title: sendKafka 
     * @Description: 将接收到的消息分发到相应的topic中 
     * @param iotp void
     * @author zhouxidong
     * @date 2018年5月27日下午2:15:06
     */
    private void sendKafka(IOTPBean iotp){
//    	switch (iotp.getType()) {
//			case 1: HandleOfIotpbeanType.type1(iotp);
//				break;
//			case 2: HandleOfIotpbeanType.type2(iotp);
//				break;
//			case 3: HandleOfIotpbeanType.type3(iotp);
//				break;
//			case 4: HandleOfIotpbeanType.type4(iotp);
//				break;
//			case 5: HandleOfIotpbeanType.type5(iotp);
//				break;
//			case 6: HandleOfIotpbeanType.type6(iotp);
//				break;
//			case 7: HandleOfIotpbeanType.type7(iotp);
//				break;
//			case 8: HandleOfIotpbeanType.type8(iotp);
//				break;	
//			case 9: HandleOfIotpbeanType.type9(iotp);
//				break;
//			case 10: HandleOfIotpbeanType.type10(iotp);
//				break;
//			case 11: HandleOfIotpbeanType.type11(iotp);
//				break;
//			case 12: HandleOfIotpbeanType.type12(iotp);
//				break;
//			case 13: HandleOfIotpbeanType.type13(iotp);
//				break;
//			case 14: HandleOfIotpbeanType.type14(iotp);
//				break;
//			case 15: HandleOfIotpbeanType.type15(iotp);
//				break;
//			case 16: HandleOfIotpbeanType.type16(iotp);
//				break;
//			default:
//				break;
//		}
    }
    
}